package com.example.redisdemo.netty.server;

import com.example.redisdemo.netty.init.WsServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * @author hexinglin
 * Server启动类
 * @created 2022-05-26 13:56
 **/
@Component
public class WSServer {

    private static class SingletionWSServer {
        static final WSServer instance = new WSServer();
    }

    public static WSServer getInstance() {
        return SingletionWSServer.instance;
    }

    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap server;
    private ChannelFuture future;

    public WSServer() {
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                //添加自定义初始化处理器
                .childHandler(new WsServerInitializer());
    }

    public void start() {
        this.future = server.bind(8899);
        System.out.println("netty websocket server 启动完毕...");
    }

    public static void main(String[] args) {
        WSServer.getInstance().start();
    }
}
